<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\Notice;
use App\Models\Order;
use App\Models\User;
use App\Models\WriteOff;
use Illuminate\Support\Facades\DB;
use Exception;

class WriteOffService extends BaseService
{
    /**
     * 核销
     * @param $uid
     * @param $orderId
     * @param $sellType
     * @param $sellId
     * @return void
     * @throws BusinessException
     */
    public function writeOff($uid, $orderId, $sellType, $sellId)
    {
        // 获取订单
        $order = Order::query()->where(['id' => $orderId])->first();
        if (!$order) {
            $this->throwBusinessException('订单不存在');
        } elseif ($order->state != Order::STATE_WAIT_USE) {
            $this->throwBusinessException('订单非待使用状态');
        }

        // 获取已核销
        $writeSellList = WriteOff::query()->where('order_id', $orderId)->get(['id', 'sell_type', 'sell_id'])->toArray();
        $writeSellType = array_column($writeSellList, 'sell_type');
        if (in_array($sellType, $writeSellType)) {
            $this->throwBusinessException(Order::sellTypeMap()[$sellType] . '已核销');
        }

        $time = date('Y-m-d H:i:s');
        DB::beginTransaction();
        try {
            // 订单
            $order->use_num = $order->pre_num;
            if ($order->sell_type == Order::SELL_COMBO) {
                $sellMulti = json_decode($order->sell_multi_json, true) ?? [];
                $allSellType = array_column($sellMulti, 'sell_type');
                $allSellId = array_column($sellMulti, 'id');
                if (!in_array($sellType, $allSellType)) {
                    throw new Exception('售卖类型有误');
                }
                $waitSellType = array_diff($allSellType, $writeSellType);
                if (empty($waitSellType)) {
                    $order->write_off_time = $time;
                    $order->state = Order::STATE_USED;
                }
                $sellMulti = array_column($sellMulti, null, 'sell_type');
                $sellJson = $sellMulti[$sellType];
                $payPrice = $sellJson['price'];
                if ($sellJson['id'] != $sellId) {
                    throw new Exception('售卖ID有误');
                }
                // 添加消息
                NoticeService::getInstance()->add(Notice::TYPE_ORDER, $order->id, $order->user_id, $sellJson['name'] . '订单已完成');
                $sellJson = json_encode($sellJson);
            } else {
                if ($order->sell_type != $sellType) {
                    throw new Exception('售卖类型有误');
                }
                if ($order->sell_id != $sellId) {
                    throw new Exception('售卖ID有误');
                }
                // 添加消息
                $sellJson = json_decode($order->sell_json, true);
                NoticeService::getInstance()->add(Notice::TYPE_ORDER, $order->id, $order->user_id, $sellJson['name'] . '订单已完成');
                $payPrice = $order->pay_price;
                $sellJson = $order->sell_json;
                $order->write_off_time = $time;
                $order->state = Order::STATE_USED;
            }
            $order->save();

            // 核销
            $writeOffData = [
                'wouser_id' => $uid,
                'user_id' => $order->user_id,
                'camp_id' => $order->camp_id,
                'order_id' => $orderId,
                'sell_type' => $sellType,
                'sell_id' => $sellId,
                'order_sn' => $order->order_sn,
                'pay_price' => $payPrice,
                'sell_json' => $sellJson,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            Db::table('write_off')->insertGetId($writeOffData);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            $this->throwBusinessException($e->getMessage());
        }
    }

    /**
     * 核销记录
     * @param $uid
     * @param $page
     * @param $pageSize
     * @return mixed
     */
    public function writeOffRecord($uid, $page, $pageSize)
    {
        // 设置对象
        $model = WriteOff::query();
        // 获取列表
        $result = $model
            ->where(['wouser_id' => $uid])
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['id', 'wouser_id', 'user_id', 'order_id', 'sell_type', 'sell_id', 'order_sn', 'pay_price', 'sell_json', 'created_at'], 'page', $page);

        // 核销用户
        $wOUserNames = [];
        if ($wouserIds = $result->getCollection()->pluck('wouser_id')) {
            $wouserIds = array_filter($wouserIds->toArray());
            $wOUserNames = User::query()->whereIn('id', $wouserIds)->pluck('name', 'id')->toArray() ?? [];
        }
        // 用户
        $userNames = [];
        if ($userIds = $result->getCollection()->pluck('user_id')) {
            $userIds = array_filter($userIds->toArray());
            $userNames = User::query()->whereIn('id', $userIds)->pluck('name', 'id')->toArray() ?? [];
        }
        // 订单
        $orderList = [];
        if ($orderIds = $result->getCollection()->pluck('order_id')) {
            $orderIds = array_filter($orderIds->toArray());
            $orderList = Order::query()->whereIn('id', $orderIds)->get(['id', 'phone', 'pre_num', 'use_num'])->toArray() ?? [];
            $orderList = array_column($orderList, null, 'id');
        }
        $result->getCollection()->transform(function ($item) use ($wOUserNames, $userNames, $orderList) {
            $item = json_decode($item, true);
            $item['sell_json'] = json_decode($item['sell_json'], true);
            $item['sell_json']['img'] = storage($item['sell_json']['img']);
            $item['wxuser_name'] = $wOUserNames[$item['wouser_id']] ?? '';
            $item['user_name'] = $userNames[$item['user_id']] ?? '';
            $item['phone'] = $orderList[$item['order_id']]['phone'] ?? '';
            $item['pre_num'] = $orderList[$item['order_id']]['pre_num'] ?? '';
            $item['use_num'] = $orderList[$item['order_id']]['use_num'] ?? '';
            return $item;
        });

        return $this->successPage($result);
    }
}
